//
//  ZegoBaseAudioVideoForegroundView.swift
//  ZegoUIKitSDK
//
//  Created by zego on 2023/2/13.
//

import UIKit
/// 定义一个协议，用于处理 ZegoBaseAudioVideoForegroundView 相关的事件回调
public protocol ZegoBaseAudioVideoForegroundViewDelegate:AnyObject {
    /// 当前景视图创建完成时调用
    func onForegroundViewCreated(_ uikitUser: ZegoUIKitUser?)
    /// 当摄像头状态改变时调用
    func onCameraStateChanged(_ isCameraOn: Bool)
    /// 当麦克风状态改变时调用
    func onMicrophoneStateChanged(_ isMicrophoneOn: Bool)
    /// 当房间内属性更新时调用
    func onInRoomAttributesUpdated(_ inRoomAttributes: [String : String])
}

// 为协议提供默认实现，这样遵循协议的类可以选择不实现这些方法
extension ZegoBaseAudioVideoForegroundViewDelegate {
    func onForegroundViewCreated(_ uikitUser: ZegoUIKitUser?){ }
    func onCameraStateChanged(_ isCameraOn: Bool) { }
    func onMicrophoneStateChanged(_ isMicrophoneOn: Bool) { }
    func onInRoomAttributesUpdated(_ inRoomAttributes: [String : String]) { }
}

/// 定义一个公开的基类，继承自 UIView，用于处理音视频前景视图的基本逻辑
open class ZegoBaseAudioVideoForegroundView: UIView {
    /// 弱引用委托对象，用于传递事件回调
    public weak var delegate: ZegoBaseAudioVideoForegroundViewDelegate?
    /// 存储用户 ID 的私有属性
    fileprivate var userID: String?
    
    public init(frame: CGRect, userID: String?, delegate: ZegoBaseAudioVideoForegroundViewDelegate?) {
        super.init(frame: frame)
        /// 向 ZegoUIKit 共享实例添加事件处理程序
        ZegoUIKit.shared.addEventHandler(self)
        self.userID = userID
        self.delegate?.onForegroundViewCreated(ZegoUIKit.shared.getUser(userID ?? ""))
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

/// 扩展 ZegoBaseAudioVideoForegroundView 类，使其遵循 ZegoUIKitEventHandle 协议
extension ZegoBaseAudioVideoForegroundView: ZegoUIKitEventHandle {
    /// 当摄像头状态改变时调用
    open func onCameraOn(_ user: ZegoUIKitUser, isOn: Bool) {
        if self.userID == user.userID {
            self.delegate?.onCameraStateChanged(isOn)
        }
    }
    /// 当麦克风状态改变时调用
    open func onMicrophoneOn(_ user: ZegoUIKitUser, isOn: Bool) {
        if self.userID == user.userID {
            self.delegate?.onMicrophoneStateChanged(isOn)
        }
    }
    
    /// 当房间内用户属性更新时调用
    open func onUsersInRoomAttributesUpdated(_ updateKeys: [String]?, oldAttributes: [ZegoUserInRoomAttributesInfo]?, attributes: [ZegoUserInRoomAttributesInfo]?, editor: ZegoUIKitUser?) {
        guard let attributes = attributes else { return }
        for attribute in attributes {
            if let userID = self.userID,
               userID == attribute.userID
            {
                self.delegate?.onInRoomAttributesUpdated(attribute.attributes)
            }
        }
    }
}
